let mongoose = require("mongoose");
let connection = require("./connection.js");
// 定义集合文档 => 定义Schema
let UserSchema = new mongoose.Schema({
  name: String,
  age: Number
});
// 定义一个模型
let userModel = connection.model("user", UserSchema);
let ScoreSchema = new mongoose.Schema({
  // uid是一个外键,类型是ObjectId,引用的是userModel模型
  uid: { type: mongoose.Types.ObjectId, ref: "user" },
  grade: Number
});
let scoreModel = connection.model("score", ScoreSchema);
(async (scoreId) => {
//   let user = await userModel.create({
//     name: "雷超1",
//     age: 27
//   }); // 先创建主表
//   let score = await scoreModel.create({
//     uid: user._id,
//     grade: 90
//   });
//   console.log(user, score);
// 根据scoreId找到user信息，因为score的外键指向的是user主键
// populate意思是填充，意思是把score信息字段中的uid填充为一个user对象
let score = await scoreModel.findById(scoreId).populate('uid')
console.log(score.uid);// 
// {
//     _id: 5ddc97e12fc7948c17785483,
//     uid: { _id: 5ddc97e12fc7948c17785482, name: '雷超1', age: 27, __v: 0 },
//     grade: 90,
//     __v: 0
// }
process.exit(0);
})('5ddc97e12fc7948c17785483');
